import React, { useRef, useEffect } from "react";
import * as monaco from "monaco-editor";
import "./provideCompletion";

function MonacoEditor({ value = "", language = "xml", theme = "hc-black", editorOptions = {}, height = "500px", width = "500px", onChange }) {
    const containerRef = useRef(null);
    const editorRef = useRef(null);

    useEffect(() => {
        if (containerRef.current) {
            // 合并默认配置和父组件传入配置
            const options = {
                value,
                language,   // 默认语言
                theme,         // 默认主题
                automaticLayout: true,
                fontSize: 14,
                minimap: { enabled: false },
                ...editorOptions,         // 父组件传入的配置覆盖默认配置
            };

            editorRef.current = monaco.editor.create(containerRef.current, options);

            const model = editorRef.current.getModel();
            const changeDisposable = model.onDidChangeContent(() => {
                const newValue = model.getValue();
                if (onChange) onChange(newValue);
            });
        }

        return () => {
            if (editorRef.current) {
                editorRef.current.dispose();
                editorRef.current = null;
            }
        };
    }, []); // 只初始化一次

    // 监听外部value变更，同步更新编辑器内容
    useEffect(() => {
        if (editorRef.current) {
            const model = editorRef.current.getModel();
            if (value !== model.getValue()) {
                model.setValue(value);
            }
        }
    }, [value]);

    return (
        <div
            ref={containerRef}
            style={{ width: width, height: height, border: "1px solid #eee" }}
        />
    );
}

export default MonacoEditor;
